package com.pocketsweet.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLAuthentication;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.SelfFragment;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_indentification)
public class Identification extends BaseActivity implements OnClickListener {

	private MLUser mlUser = new MLUser();
	int score = 0;
	public static LoadingDailog loading;
	// private int isToBeRecommend = 1;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.relPhoto)
	private static RelativeLayout relPhoto;

	@ViewInject(R.id.relProfile)
	private static RelativeLayout relProfile;

	@ViewInject(R.id.relContact)
	private static RelativeLayout relContact;

	@ViewInject(R.id.relTest)
	private static RelativeLayout relTest;

	// @ViewInject(R.id.checkBtnToBeRecommend)
	// private static ToggleButton checkBtnToBeRecommend;
	//
	// @ViewInject(R.id.edtContact)
	// private static EditText edtContact;

	@ViewInject(R.id.tvMyPhotoStatus)
	private static TextView tvMyPhotoStatus;

	@ViewInject(R.id.tvMyProfileStatus)
	private static TextView tvMyProfileStatus;

	@ViewInject(R.id.tvTestStatus)
	private static TextView tvTestStatus;

	@ViewInject(R.id.tvContactStatus)
	private static TextView tvContactStatus;

	public static boolean isFinishTest = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		initView();
		setHeaderFunction();
	}

	@Override
	protected void onResume() {
		super.onResume();
		calculateProfile();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (IdentificationPhoto.photo != null) {
			IdentificationPhoto.photo = null;
		}
		if (IdentificationPhoto.cropPath != null) {
			IdentificationPhoto.cropPath = null;
		}
		if (!StringUtils.isEmpty(IdentificationPhoto.photoPath)) {
			IdentificationPhoto.photoPath = null;
		}
	}

	public static void setFinishTest() {
		isFinishTest = true;
	}

	public boolean getIsFinishTest() {
		return isFinishTest;
	}

	private void initView() {
		relPhoto = (RelativeLayout) findViewById(R.id.relPhoto);
		relProfile = (RelativeLayout) findViewById(R.id.relProfile);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		// checkBtnToBeRecommend = (ToggleButton)
		// findViewById(R.id.checkBtnToBeRecommend);
		// edtContact = (EditText) findViewById(R.id.edtContact);
		tvMyPhotoStatus = (TextView) findViewById(R.id.tvMyPhotoStatus);
		tvMyProfileStatus = (TextView) findViewById(R.id.tvMyProfileStatus);
		tvContactStatus = (TextView) findViewById(R.id.tvContactStatus);
		relPhoto.setOnClickListener(this);
		relProfile.setOnClickListener(this);
		relContact.setOnClickListener(this);
		relTest.setOnClickListener(this);
		// checkBtnToBeRecommend.setChecked(true); // 设置开关初始状态
		AVQuery<MLAuthentication> query = new AVQuery<MLAuthentication>(
				"MLAuthentication");
		query.whereEqualTo("sponsor", mlUser);
		query.whereEqualTo("status", C.AUTHENTICATION_STATUS_NORMAL);
		query.findInBackground(new FindCallback<MLAuthentication>() {
			public void done(List<MLAuthentication> mlAuthenticationList,
					AVException e) {
				if (e == null) {
					if (mlAuthenticationList.size() > 0) {// 已经提交过认证
						MLAuthentication mlAuthentication;
						int i;
						for (i = 0; i < mlAuthenticationList.size(); i++) {
							mlAuthentication = mlAuthenticationList.get(i);
							if (mlAuthentication.getStatus() == C.IDENTIFICATION_STATUS_WAITING) {
								ToolKits.toast(Identification.this,
										"您已有申请资料在审核中");
								break;
							}
						}
					}
				} else {
					ToolKits.toast(Identification.this, "网络似乎断开了");
				}
			}
		});
	}

	private void calculateProfile() {
		if (SelfFragment.imgsPath != null && SelfFragment.imgsPath.size() > 0) {
			score = UserService.getUserProfileIntegrity(SelfFragment.imgsPath
					.size());
			// score = UserService.getUserProfileIntegrity(8);
			setCompleteIdentification();
		} else {
			AVQuery<MLGallery> query = new AVQuery<MLGallery>("MLGallery");
			query.whereEqualTo("belong_to", mlUser);
			query.include("images");
			query.findInBackground(new FindCallback<MLGallery>() {
				public void done(List<MLGallery> gallery, AVException e) {
					if (e == null) {
						// 获取相册
						if (gallery.size() != 0) {
							score = UserService.getUserProfileIntegrity(gallery
									.size());
							// score = UserService.getUserProfileIntegrity(8);
						} else {
							score = UserService.getUserProfileIntegrity(0);
						}
						setCompleteIdentification();
					}
				}
			});
		}
	}

	private void setCompleteIdentification() {
		if (score == 100) {
			tvMyProfileStatus
					.setBackgroundResource(R.drawable.shape_rectangle_grey_apply);
			tvMyProfileStatus.setText("已完整");
		} else {
			tvMyProfileStatus
					.setBackgroundResource(R.drawable.shape_rectangle_un_apply);
			tvMyProfileStatus.setText("未完整");
		}
		// checkBtnToBeRecommend
		// .setOnCheckedChangeListener(new OnCheckedChangeListener() {
		//
		// @Override
		// public void onCheckedChanged(CompoundButton buttonView,
		// boolean checkState) {
		// if (checkState) {
		// checkBtnToBeRecommend.setChecked(true);
		// isToBeRecommend = 1;
		// } else {
		// checkBtnToBeRecommend.setChecked(false);
		// isToBeRecommend = 0;
		//
		// }
		// }
		// });
		if (!isFinishTest) {

			tvTestStatus
					.setBackgroundResource(R.drawable.shape_rectangle_un_apply);
			tvTestStatus.setText("未通过");

		} else {
			tvTestStatus
					.setBackgroundResource(R.drawable.shape_rectangle_grey_apply);
			tvTestStatus.setText("已通过");

		}
		if (StringUtils.isEmpty(IdentificationPhoto.photoPath)) {
			tvMyPhotoStatus
					.setBackgroundResource(R.drawable.shape_rectangle_un_apply);
			tvMyPhotoStatus.setText("未上传");
		} else {
			tvMyPhotoStatus
					.setBackgroundResource(R.drawable.shape_rectangle_grey_apply);
			tvMyPhotoStatus.setText("已上传");
		}
		if (mlUser.getNotifyPhone() == null
				|| mlUser.getNotifyPhone().equals("")) {
			tvContactStatus
					.setBackgroundResource(R.drawable.shape_rectangle_un_apply);
			tvContactStatus.setText("未绑定");
		} else {
			tvContactStatus
					.setBackgroundResource(R.drawable.shape_rectangle_grey_apply);
			tvContactStatus.setText("已绑定");
		}

	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("提交");
		header.setMiddleText("申请");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				if (StringUtils.isEmpty(IdentificationPhoto.photoPath)) {
					Identification.this.finish();
					return;
				}
				final MyAlertDialog dialog = new MyAlertDialog(
						Identification.this).builder()
						.setMsg("如果放弃，此次的编辑内容将不会保存，确定放弃？").setTitle("提示")
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {

							}
						});
				dialog.setPositiveButton("确定", new OnClickListener() {
					@SuppressLint("SimpleDateFormat")
					@Override
					public void onClick(View v) {
						Identification.this.finish();
					}
				});
				dialog.show();
			}
		});
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				if (StringUtils.isEmpty(IdentificationPhoto.photoPath)
						|| score != 100) {
					ToolKits.toast(Identification.this, "请完善信息");
					return;
				}
				if (mlUser.getNotifyPhone() == null
						|| mlUser.getNotifyPhone().equals("")) {
					ToolKits.toast(Identification.this, "请验证手机号");
					return;
				}

				if (!isFinishTest) {
					ToolKits.toast(Identification.this, "请先完成考试");
					return;

				}
				loading = ToolKits.createLoadingDialog(Identification.this,
						"提交中..");
				loading.setText("加载中");
				loading.show();
				final AVQuery<MLAuthentication> query = new AVQuery<MLAuthentication>(
						"MLAuthentication");
				query.whereEqualTo("sponsor", mlUser);
				query.findInBackground(new FindCallback<MLAuthentication>() {
					public void done(
							List<MLAuthentication> mlAuthenticationList,
							AVException e) {
						if (e == null) {
							if (mlAuthenticationList.size() > 0) {// 已经提交过认证
								MLAuthentication mlAuthentication;
								int i;
								for (i = 0; i < mlAuthenticationList.size(); i++) {
									mlAuthentication = mlAuthenticationList
											.get(i);
									if (mlAuthentication.getStatus() == C.IDENTIFICATION_STATUS_WAITING) {
										loading.dismiss();
										ToolKits.toast(Identification.this,
												"您已有申请资料在审核中");
										break;
									}
								}
								if (i >= mlAuthenticationList.size()) { // 可以申请
									submit();
								}
							} else {
								submit();
							}
						} else {
							ToolKits.toast(Identification.this, "网络似乎断开了");
							loading.dismiss();
						}
					}
				});
			}
		});
	}

	private void submit() {
		// mlUser.setMobilePhoneNumber(edtContact.getText().toString());
		mlUser.saveInBackground(new SaveCallback() {
			@Override
			public void done(AVException e) {
				if (e == null) {
					MLAuthentication mlAuthentication = new MLAuthentication();
					mlAuthentication.setAvatar(IdentificationPhoto.photo);
					mlAuthentication.setContact(UserService.getCurrentUser()
							.getNotifyPhone());
					mlAuthentication
							.setNeedRecommend(C.IDENTIFICATION_STATUS_NOT_TOBE);
					mlAuthentication.saveInBackground(new SaveCallback() {

						@Override
						public void done(AVException e) {
							loading.dismiss();
							if (e == null) {
								AVAnalytics.onEvent(Identification.this,
										"申请成为口袋恋人");
								final MyAlertDialog dialog = new MyAlertDialog(
										Identification.this)
										.builder()
										.setMsg("你已成功提交认证资料，正在审核中")
										.setTitle("提示")
										.setPositiveButton("确定",
												new OnClickListener() {
													@Override
													public void onClick(View v) {
														Identification.this
																.finish();
													}
												});
								dialog.show();
							} else {
								ToolKits.toast(Identification.this, "网络似乎断开了");
							}
						}
					});
				} else {
					ToolKits.toast(Identification.this, "网络似乎断开了");
					loading.dismiss();
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.relPhoto:
			Intent intentPhoto = new Intent(Identification.this,
					IdentificationPhoto.class);
			startActivity(intentPhoto);
			break;
		case R.id.relProfile:
			Intent intent = new Intent(Identification.this, ProfileEdit.class);
			startActivity(intent);
			break;

		case R.id.relTest:
			if (!isFinishTest) {
				Intent intentTest = new Intent(Identification.this,
						ApplyTest.class);
				startActivity(intentTest);

			} else {
				ToolKits.toast(Identification.this, "您已经通过考试啦！");
			}
			break;

		case R.id.relContact:

			Intent intentContact;
			if (mlUser.getNotifyPhone() == null
					|| mlUser.getNotifyPhone().equals("")) {
				intentContact = new Intent(Identification.this,
						IndentifiedMobile.class);

			} else {
				// return;
				intentContact = new Intent(Identification.this,
						IdentificationMobileConfirm.class);

			}
			startActivity(intentContact);

			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 此处写处理的事件
			Identification.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
